package cn.gp.chatclient.ui.frame;

import cn.gp.chatclient.ClientMain;
import cn.gp.chatclient.model.UserVo;
import cn.gp.chatclient.service.UserService;

import javax.swing.*;
import java.awt.*;
import java.util.function.Consumer;

/**
 * @ClassName LoginDialog
 * @Description TODO
 * @Author He Guoping
 * @Date 2025/6/17 10:13
 * @Version JDK17
 */
public class LoginDialog extends JDialog {
    private final UserService userService;
    private final Consumer<UserVo> onLoginSuccess;

    public LoginDialog(UserService userService, Consumer<UserVo> onLoginSuccess) {
        this.userService = userService;
        this.onLoginSuccess = onLoginSuccess;
        initUI();
    }

    private void initUI() {
        setTitle("用户登录");
        setSize(350, 250);
        setLocationRelativeTo(null); // 居中显示
        setModal(true); // 设置为模态对话框
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 用户名标签
        gbc.gridx = 0;
        gbc.gridy = 0;
        add(new JLabel("用户名:"), gbc);

        // 用户名输入框
        JTextField usernameField = new JTextField(15);
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        add(usernameField, gbc);

        // 密码标签
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 1;
        add(new JLabel("密码:"), gbc);

        // 密码输入框
        JPasswordField passwordField = new JPasswordField(15);
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.gridwidth = 2;
        add(passwordField, gbc);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        JButton loginBtn = new JButton("登录");
        JButton backBtn = new JButton("返回");
        buttonPanel.add(loginBtn);
        buttonPanel.add(backBtn);

        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 3;
        gbc.fill = GridBagConstraints.CENTER;
        add(buttonPanel, gbc);

        // 添加事件监听器
        loginBtn.addActionListener(e -> {
            String username = usernameField.getText().trim();
            String password = new String(passwordField.getPassword()).trim();

            if (username.isEmpty() || password.isEmpty()) {
                JOptionPane.showMessageDialog(this, "用户名和密码不能为空", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            userService.login(username, password,
                    user -> {
                        dispose();
                        onLoginSuccess.accept(user);
                    },
                    error -> JOptionPane.showMessageDialog(this, error, "登录失败", JOptionPane.ERROR_MESSAGE)
            );
        });

        backBtn.addActionListener(e -> {
            dispose();
            ClientMain.showSelectionDialog();
        });

        // 回车键登录
        getRootPane().setDefaultButton(loginBtn);
    }
}
